package com.prpat;

import java.net.ServerSocket;
import java.net.Socket;


class Listener implements Runnable
{
	@Override
	public void run() 
	{
		try
		{//TODO handle disconnection
			ServerSocket serverSock = new ServerSocket( River.CHAT_PORT );
			while(River.CONNECTED) 
			{
//				River.display.append("\n");
				System.out.println();
				Socket clientSocket = serverSock.accept();
				
				synchronized (clientSocket)
				{
					if (!River.iAmServer()) 
					{
						if (TaskCounter.count() > 1) {
							Thread t = new Thread(new PassToNext(clientSocket));
							t.start();
							continue;
						} else {
							TaskCounter.increment();
						}
					}
				}
				Thread t = new Thread(new MessageHandler(clientSocket));
				t.setName("MessageHandler");
				t.start();
			}
		}
		catch (Exception ex) 
		{ 
			System.err.println("Error in chat server");
		}
	}

}
